package xyz.weizhi.tanhua.appserver.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import xyz.weizhi.commons.utils.JwtUtils;
import xyz.weizhi.tanhua.appserver.Exception.BusinessException;
import xyz.weizhi.tanhua.autoconfig.Tempalte.SmsTemplate;
import xyz.weizhi.tanhua.dubbo.api.UserApi;
import xyz.weizhi.tanhua.model.domain.User;
import xyz.weizhi.tanhua.model.vo.ErrorResult;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author milian
 * @Date 2021/10/21 0021 14:40
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @DubboReference
    private UserApi userApi;
    // TODO 记得加泛型
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    public void sendMsg(String phone) {
        //String code = RandomStringUtils.randomNumeric(6);
        String code ="123456";
        //smsTemplate.SendSms(phone, code);
        log.info("code:{}",code);
        redisTemplate.opsForValue().set("Cache_Code_"+phone, code, Duration.ofMinutes(5));
    }

    public Map loginVerification(String phone, String verificationCode) {
        // 获取缓存在redis数据库的验证码
        String Cache_Code = redisTemplate.opsForValue().get("Cache_Code_"+phone);
        if (!StringUtils.isNotEmpty(Cache_Code)||!Cache_Code.equals(verificationCode)){
            throw new BusinessException(ErrorResult.loginError());
        }
        // 登录成功
        User user = userApi.findUserByPhone(phone);
        boolean isNew = false;
        if (user==null){
             user = new User();
             user.setMobile(phone);
             user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;
        }
        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;
    }

    public boolean checkVerificationCode(String mobile, String verificationCode) {
        String Cache_Code = redisTemplate.opsForValue().get("Cache_Code_"+mobile);
        if (!StringUtils.isNotEmpty(Cache_Code)||!Cache_Code.equals(verificationCode)){
            throw new BusinessException(ErrorResult.loginError());
        }
        redisTemplate.delete("Cache_Code_"+mobile);
        return true;
    }
}
